﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Office = Microsoft.Office.Core;
using Tools = Microsoft.Office.Tools;
using Word = Microsoft.Office.Interop.Word;
using eRechnung_3_0.Properties;


namespace eRechnung_3_0
{
    // SVN Info
    // LastChangedRevision  $LastChangedRevision: 126 $
    // LastChangedDate      $LastChangedDate: 2009-12-18 16:23:55 +0100 (Fri, 18 Dec 2009) $
    // HeadURL              $HeadURL: svn://bpcsrv/ebInterface/eRechnung%203.0/tags/Vers 2 Rev 0 Mod 0 RC1/eRechnung 3.0/ThisDocument.cs $
    // Revision             $Revision: 126 $
    // Author               $Author: jbogad $
    // Date                 $Date: 2009-12-18 16:23:55 +0100 (Fri, 18 Dec 2009) $
    // LastChangedBy        $LastChangedBy: jbogad $
    // ID                   $Id: ThisDocument.cs 126 2009-12-18 15:23:55Z jbogad $
    // Header               $Header: svn://bpcsrv/ebInterface/eRechnung%203.0/tags/Vers 2 Rev 0 Mod 0 RC1/eRechnung 3.0/ThisDocument.cs 126 2009-12-18 15:23:55Z jbogad $

    public partial class ThisDocument
    {

        public ebInterfaceTableManager XlateTables;
        public InvoiceXSD InvXSD;
        [CachedAttribute] public string InvoiceXMLPartID = string.Empty;
        public Office.CustomXMLPart InvoiceXMLPart;
        private InvoiceXML invXML = new InvoiceXML();
        private object pwd = "AustriaPro";
        public decimal BetragExklMwSt = 0;
        public decimal BetragInklMwSt = 0;
        public decimal BetragMwSt = 0;
        public DateTime Rechnungsdatum = DateTime.Today;
        public DateTime FaelligDatum = DateTime.Today;
        public bool DatumHasChanged = false;

        private bool DocIsProtected = false;

        #region Details
        // Tabellenkopf
        //1 Pos.
        //2 ArtikelNr	
        //3 Bezeichnung	
        //4 Menge	
        //5 Einheit	
        //6 Einzelpreis	
        //7 Rabatt%	
        //8 MwSt%	
        //9 Gesamtbetrag 

        // Tabelle die die Spalten in Word Tabelle und DataSet-Table mapped
        // die Columnnamen sind in der Reihenfolge der Spalten im Word Dok geordnet
        // ACHTUNG: die erste Spalte ist die Positionsnummer
        private string[] dtDetailsColName = {"spArtikelNr",    // -> pos 2!
                                  "spBezeichnung",  
                                  "spMenge",
                                  "SpEinheit",
                                  "spEinzelPreis",
                                  "spRabattProz",
                                  "spMwst",
                                  "spGesamtBetrag"};

        private string[] dtDetailsColFmt = {"",    // -> pos 2!
                                  "",  
                                  "#,##0.00",
                                  "",
                                  "#,##0.00",
                                  "0.00%",
                                  "0.00%",
                                  "#,##0.00"};
        
        #endregion
        #region MwST
        // Mehrwertsteuertabelle
        //1 MwSt %	
        //2 Basisbetrag	
        //3 MwSt Betrag	
        //4 Gesamtbetrag

        private string[] dtMwStColName = {"spMwSt", 
                                          "spBasisBetrag",
                                          "spMwStBetrag",
                                          "spGesamtBetrag"
                                         };
        private string[] dtMwStColFmt ={"0.00%",
                                        "#,##0.00",
                                        "#,##0.00",
                                        "#,##0.00"};

        #endregion
        #region Skonto
        // Skontotabelle
        //1 Bis Datum	
        //2 Tage
        //3 Skonto%	
        //4 BasisBetrag
        //3 Skonto Betrag
        private string[] dtSkontoColName = { "SpBisDatum", "SpTage", "SpSkontoProz", "spBasisBetrag", "spSkontoBetrag" };
        private string[] dtSkontoColFmt = { "dd", "0", "0.00%", "#,##0.00", "#,##0.00" };
        
        #endregion
        private const int docDetailsTab = 2;    // Nummer der Detailstabelle im Word Dokument
        private const int docMwstTab = 3;       // NUmmer der Mehrwehrtsteuertabelle im Dokument
        private const int docSkontoTab = 4;     // Nummer der Skontotabelle

        #region Startup und Shutdown Funktionen
        private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
            SetRibbonButtonsEnable(false);      // Ribbon disabled
            Word.Document doc = eRechnung_3_0.Globals.ThisDocument.Application.ActiveDocument;

            XlateTables = new ebInterfaceTableManager();
            InvXSD = new InvoiceXSD();

            if (doc.ProtectionType != Word.WdProtectionType.wdNoProtection)
            {
                UnprotectDoc();
            }
            string xmldata = invXML.GetFromXMLResource();
            LoadXML2CustomPart(xmldata);       // Laden der XML Daten
            ProtectDoc();
            UpdateDocDetails();     // muss nach ProtectDoc() stehen, da das doc temp wieder unprotected wird
        }

        private void ThisDocument_Shutdown(object sender, System.EventArgs e)
        {
        }

        //protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
        //{
        //    return new eRechung_Ribbon();
        //}
        #endregion

        #region Vom VSTO-Designer generierter Code

        /// <summary>
        /// Erforderliche Methode für die Designerunterstützung.
        /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
        /// </summary>
        private void InternalStartup()
        {
            this.CC_RecipientVATID.Validating += new System.ComponentModel.CancelEventHandler(this.CC_RecipientVATID_Validating);
            this.CC_InvoiceDate.StoreUpdating += new System.EventHandler<Microsoft.Office.Tools.Word.ContentControlStoreUpdatingEventArgs>(this.CC_InvoiceDate_StoreUpdating);
            this.CC_DueDate.StoreUpdating += new System.EventHandler<Microsoft.Office.Tools.Word.ContentControlStoreUpdatingEventArgs>(this.CC_DueDate_StoreUpdating);
            this.Shutdown += new System.EventHandler(this.ThisDocument_Shutdown);
            this.Startup += new System.EventHandler(this.ThisDocument_Startup);

        }

        #endregion

        #region Dokumentenbehandlung
        public void SetFehlerText(string text)
        {
            CC_Fehlerliste.LockContents = false;
            CC_Fehlerliste.Text = text;
            CC_Fehlerliste.LockContents = true;
        }
        public void Settings2Doc(DsInvoice myDs)
        {
            this.CC_BillerName.Text = Settings.Default.setName;
            this.CC_BillerStreet.Text = Settings.Default.setStrasse;
            this.CC_BillerTown.Text = Settings.Default.setOrt;
            this.CC_BillerZip.Text = Settings.Default.setPLZ;
            SelectDropDownValue(this.CC_BillerCountry.DropDownListEntries,Settings.Default.setLand);
            this.CC_BillerPhone.Text=Settings.Default.setTelNr;
            this.CC_BillerEmail.Text=Settings.Default.setEmail;
            this.CC_BillerVATID.Text= Settings.Default.setVATID;
            this.CC_BillerContact.Text=Settings.Default.setBillerContact;

            SelectDropDownValue(this.CC_Currency.DropDownListEntries, Settings.Default.setWhrg);

            this.CC_BankName.Text=Settings.Default.setBank;
            this.CC_BankAccountNr.Text=Settings.Default.setKontonr;
            this.CC_BankAccountOwner.Text= Settings.Default.setKontowortlaut;
            this.CC_BankCode.Text=Settings.Default.setBLZ;
            this.CC_BankIBAN.Text =Settings.Default.setIBAN;

            SelectDropDownValue(this.CC_BankCountry.DropDownListEntries, Settings.Default.setBankLand);
            CopyTable(myDs, invXML.InvDetails, myDs.TblMWST.TableName);
            return;
        }
        /// <summary>
        /// Initialisiert alle COntrols in der Vorlage und verbindet diese mit XML Tags
        /// </summary>
        private void InitDoc()
        {
            MapPlainTextControl(this.CC_BillerName, InvoiceXML.xPathBillerName, Settings.Default.setName);
            MapPlainTextControl(this.CC_BillerStreet, InvoiceXML.xPathBillerStreet, Settings.Default.setStrasse);
            MapPlainTextControl(this.CC_BillerTown, InvoiceXML.xPathBillerTown, Settings.Default.setOrt);
            MapPlainTextControl(this.CC_BillerZip, InvoiceXML.xPathBillerZip, Settings.Default.setPLZ);
            FillCountry(this.CC_BillerCountry, InvoiceXML.xPathBillerCountry, Settings.Default.setLand);
            MapPlainTextControl(this.CC_BillerPhone, InvoiceXML.xPathBillerPhone, Settings.Default.setTelNr);
            MapPlainTextControl(this.CC_BillerEmail, InvoiceXML.xPathBillerEmail, Settings.Default.setEmail);
            MapPlainTextControl(this.CC_BillerVATID, InvoiceXML.xPathBillerVATID, Settings.Default.setVATID);
            MapPlainTextControl(this.CC_BillerContact, InvoiceXML.xPathBillerContact, Settings.Default.setBillerContact);

            MapPlainTextControl(this.CC_RecipientSalutation, InvoiceXML.xPathInvRecSalute, "");
            MapPlainTextControl(this.CC_RecipientName, InvoiceXML.xPathInvRecName, "");
            MapPlainTextControl(this.CC_RecipientStreet, InvoiceXML.xPathInvRecStreet, "");
            MapPlainTextControl(this.CC_RecipientTown, InvoiceXML.xPathInvRecTown, "");
            MapPlainTextControl(this.CC_RecipientZip, InvoiceXML.xPathInvRecZip, "");
            FillCountry(this.CC_RecipientCountry, InvoiceXML.xPathInvRecCountry, "Österreich");
            MapPlainTextControl(this.CC_RecipientPhone, InvoiceXML.xPathInvRecPhone, "");
            MapPlainTextControl(this.CC_RecipientEmail, InvoiceXML.xPathInvRecEmail, "");
            MapPlainTextControl(this.CC_RecipientVATID, InvoiceXML.xPathInvRecVATID, "00000000");
            MapPlainTextControl(this.CC_RecipientContact, InvoiceXML.xPathInvRecContact, "");

            FillDocumentType(this.CC_InvoiceType, InvoiceXML.xPathDocumentType, "Invoice");

            MapPlainTextControl(this.CC_BillersReceipientID, InvoiceXML.xPathInvRecBillerID, "");

            MapDateControl(this.CC_InvoiceDate, InvoiceXML.xPathInvDate, Rechnungsdatum.ToString("yyyy-MM-dd"));
            MapPlainTextControl(this.CC_InvoiceNumber, InvoiceXML.xPathInvNumber, "");

            MapPlainTextControl(this.CC_OrderReference, InvoiceXML.xPathOrderRefID, "");

            MapDateControl(this.CC_OrderDate, InvoiceXML.xPathOrderRefDate, "");

            MapDateControl(this.CC_DeliverydateStart, InvoiceXML.xPathDeliveryDate, Rechnungsdatum.ToString("yyyy-MM-dd"));

            FillCurrency(this.CC_Currency, InvoiceXML.xPathCurrency, Settings.Default.setWhrg);
            MapDateControl(this.CC_DueDate, InvoiceXML.xPathPaymtDuedate, Rechnungsdatum.ToString("yyyy-MM-dd"));

            MapPlainTextControl(this.CC_BankName, InvoiceXML.xPathBankName, Settings.Default.setBank);
            MapPlainTextControl(this.CC_BankAccountNr, InvoiceXML.xPathBankAcctNr, Settings.Default.setKontonr);
            MapPlainTextControl(this.CC_BankAccountOwner, InvoiceXML.xPathBankAcctOwner, Settings.Default.setKontowortlaut);
            MapPlainTextControl(this.CC_BankCode, InvoiceXML.xPathBankBLZ, Settings.Default.setBLZ);
            MapPlainTextControl(this.CC_BankIBAN, InvoiceXML.xPathBankIBAN, Settings.Default.setIBAN);

            FillCountry(this.CC_BankCountry, InvoiceXML.xPathBankLand, Settings.Default.setBankLand);

            MapPlainTextControl(this.CC_Rechnungsbetrag, InvoiceXML.xPathTotGrossAmount, "");
        }
        /// <summary>
        /// Setzt 
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="xPath"></param>
        /// <param name="setting"></param>
        private void FillDocumentTitle(Tools.Word.DatePickerContentControl ctrl,
                        string xPath,
                        string setting)
        {
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(xPath);
            if (vnode.Text == "")
            {
                vnode.Text = setting;
            }
            ctrl.Text = vnode.Text;
        }
        private void MapDateControl(Tools.Word.DatePickerContentControl ctrl,
                        string xPath,
                        string setting)
        {
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(xPath);
            if (vnode.Text == "")
            {
                vnode.Text = setting;
            }
            // ctrl.Tag = xPath;
            ctrl.XMLMapping.SetMapping(xPath, InvoiceXML.Prefix, InvoiceXMLPart);
        }
        /// <summary>
        /// Erstellt das Mapping zwischen Control im Dokument und XML
        /// </summary>
        /// <param name="ctrl">Word Control</param>
        /// <param name="xPath">xPath in XML</param>
        /// <param name="setting">Default Wert</param>
        private void MapPlainTextControl(Tools.Word.PlainTextContentControl ctrl,
                        string xPath,
                        string setting)
        {
            string XMLField = xPath;
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(XMLField);

            if (vnode.Text == "")
            {
                vnode.Text = setting;
            }
            // ctrl.Tag = xPath;
            ctrl.XMLMapping.SetMapping(XMLField, InvoiceXML.Prefix, InvoiceXMLPart);

        }
        /// <summary>
        /// Füllt ein DropDown Control
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="values"></param>
        /// <param name="selection"></param>
        private void FillDropDownList(Tools.Word.DropDownListContentControl ctrl, string[] values, string selection)
        {
            ctrl.DropDownListEntries.Clear();
            int ictr = 0;
            foreach (string wert in values)
            {
                ctrl.DropDownListEntries.Add(wert, wert, ictr);
                ictr++;
            }

            SelectDropDownValue(ctrl.DropDownListEntries, selection);
        }
        /// <summary>
        /// Füllt das Währungscontrol
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="xPath"></param>
        /// <param name="defVal"></param>
        private void FillCurrency(Tools.Word.DropDownListContentControl ctrl, string xPath, string defVal)
        {
            string[] docType = InvXSD.GetAllCurrencies();
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(xPath);
            string sel = defVal;
            if (vnode != null)
            {
                sel = vnode.Text;
            }

            FillDropDownList(ctrl, docType, sel);

        }
        /// <summary>
        /// Füllt den Dokumententyp auf Deutsch
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="xPath"></param>
        /// <param name="defVal"></param>
        private void FillDocumentType(Tools.Word.DropDownListContentControl ctrl, string xPath, string defVal)
        {
            // string[] docType = InvXSD.GetAllInvoiceTypes();
            string[] docType = XlateTables.GetAllGerDocTypes();
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(xPath);
            string sel = defVal;
            if (vnode != null)
            {
                sel = vnode.Text;
            }

            FillDropDownList(ctrl, docType, XlateTables.FindDocTypeGerman(sel));

        }
        /// <summary>
        /// Füllt das Land und übersetzt dabei zwischen Langtext und Abkürzung
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="xPath"></param>
        /// <param name="defVal"></param>
        private void FillCountry(Tools.Word.DropDownListContentControl ctrl, string xPath, string defVal)
        {
            String[] Countries = XlateTables.GetAllCountries();
            // Aktuellen Wert wählen
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(xPath);

            // defVal = "" -> keine Defaultwerte
            string sel = XlateTables.FindShortcut(defVal);

            if (vnode.Text != "")
            {
                sel = vnode.Text;
            }
            string selection = "";

            if (sel != "")
            {
                selection = XlateTables.FindLand(sel);
            }
            FillDropDownList(ctrl, Countries, selection);

        }
        /// <summary>
        /// Selektiert einen Wert in der ContentControlList
        /// </summary>
        /// <param name="myLe"></param>
        /// <param name="wert"></param>
        private void SelectDropDownValue(Word.ContentControlListEntries myLe, string wert)
        {
            foreach (Word.ContentControlListEntry myEntry in myLe)
            {
                if (myEntry.Value == wert)
                {
                    myEntry.Select();
                }
            }
        }
        #endregion


        #region Hilfsfunktionen
        /// <summary>
        /// Setzt bei den Ribbon Buttons die Eigenschaft Enabeled
        /// </summary>
        /// <param name="enable">true oder false</param>
        public void SetRibbonButtonsEnable(bool enable)
        {
            Globals.Ribbons.ebI_Ribbon.BtnSave.Enabled = enable;
            Globals.Ribbons.ebI_Ribbon.BtnSkonto.Enabled = enable;
            Globals.Ribbons.ebI_Ribbon.BtnDetails.Enabled = enable;
        }

        /// <summary>
        /// Dokument schützen
        /// </summary>
        public void ProtectDoc()
        {
            if (DocIsProtected==true)
            {
                return;
            }
            ThisApplication.ActiveDocument.Protect(
                Microsoft.Office.Interop.Word.WdProtectionType.wdAllowOnlyFormFields,
                ref missing,
                ref pwd,
                ref missing,
                ref missing);
            DocIsProtected = true;

        }

        /// <summary>
        /// Dokumentenschutz aufheben
        /// </summary>
        public void UnprotectDoc()
        {
            if (DocIsProtected==false)
            {
                return;
            }
            
            ThisApplication.ActiveDocument.Unprotect(ref pwd);
            DocIsProtected = false;
        }        

        public void LoadXML2CustomPart(string xmldata)
        {
            InvoiceXMLPart = invXML.AddCustomXmlPart(xmldata);
            invXML.InvDetails.LoadMwStTab();
            bool retVal = invXML.LoadDetailsTable(InvoiceXMLPart, invXML.InvDetails);
            InitDoc();
            invXML.LoadSkontoTable(InvoiceXMLPart, invXML.InvDetails); // Muss nach InitDoc liegen damit auf die ContentControls zugegriffen werden kann
        }

        /// <summary>
        /// Formattiert einen string als Datum, decimal oder Prozent für die Anzeige im Word ebDoc
        /// </summary>
        /// <param name="Format">Format Angabe entstprechend string.Format</param>
        /// <param name="wert">Datenwert</param>
        /// <returns></returns>
        private string FormatDecimal(string Format, string wert)
        {
            string retval = string.Empty;
            string form = Format;
            if (form.StartsWith("d"))
            {
                DateTime val;
                if (wert!=null)
                {
                    val = DateTime.Parse(wert);
                    form = form.Substring(1, form.Length - 1);
                    retval = val.ToString(form); //, System.Globalization.CultureInfo.InvariantCulture);
                }
            } else 
            {
                decimal val = 0;
                if (wert != "")
                {
                    val = decimal.Parse(wert); ;

                }
                else
                {
                    val = 0;
                }
                if (form.EndsWith("%") == true)
                {
                    val /= 100;         // Prozentwert
                }
                retval = val.ToString(form); //, System.Globalization.CultureInfo.InvariantCulture);
                
            }

            return (retval);
        }
        /// <summary>
        /// Kopiert die angegebene Tabelle von einem DAtaset in das andere
        /// </summary>
        /// <param name="vonDs">von Dataset</param>
        /// <param name="nachDs">nach Dataset</param>
        /// <param name="tabName">Name der Tabelle</param>
        public void CopyTable(DsInvoice vonDs, DsInvoice nachDs, string tabName)
        {
            DataTable von = vonDs.Tables[tabName];
            DataTable nach = nachDs.Tables[tabName];
            nach.Clear();
            foreach (DataRow Row in von.Rows)
            {
                nach.Rows.Add(Row.ItemArray); // Zeile kopieren
            }
        }
        /// <summary>
        /// Skontotabelle aus dem Form zurück in die eigene Tab kopieren
        /// und das ebDoc updaten
        /// </summary>
        /// <param name="myDs"></param>
        public void SaveSkonto(DsInvoice myDs)
        {
            CopyTable(myDs, invXML.InvDetails, myDs.TblInvSkonto.TableName);
            // UpdateDocDetails();
            FillSkontoTabInDoc();
        }
        /// <summary>
        /// Details aus dem Form in die eigne Tab kopieren 
        /// und das ebDoc updaten
        /// </summary>
        /// <param name="myDs"></param>
        public void SaveDetails(DsInvoice myDs)
        {
            CopyTable(myDs, invXML.InvDetails, myDs.TblInvDetails.TableName);
            UpdateDocDetails();
        }
        /// <summary>
        /// MWST Summentabelle aufbauen
        /// </summary>
        private void FillMwStTabInDoc()
        {
            // 1. Summen berechnen
            invXML.InvDetails.TblMwStSummen.Clear(); // alle Daten löschen
            System.Nullable<Decimal> SummeExklMwSt = 0;
            System.Nullable<Decimal> SummeInklMwSt = 0;
            System.Nullable<Decimal> SummeMwSt = 0;
            decimal mwst = 0;
            DsInvoice.TblMwStSummenRow mwstRow = null;
            BetragExklMwSt = 0;
            BetragInklMwSt = 0;
            BetragMwSt = 0;

            foreach (DsInvoice.TblMWSTRow rMWST in invXML.InvDetails.TblMWST)
            {
                mwst = rMWST.SpMwSt;
                SummeExklMwSt = (from InvoiceDetail in invXML.InvDetails.TblInvDetails 
                             where (InvoiceDetail.SpMwSt == mwst)
                             select InvoiceDetail.SpGesamtBetrag  ).Sum();
                if (SummeExklMwSt != 0)
                {
                    mwstRow = (DsInvoice.TblMwStSummenRow) invXML.InvDetails.TblMwStSummen.Rows.Add();
                    mwstRow.spMwSt = mwst;
                    mwstRow.spBasisBetrag = SummeExklMwSt.Value;
                    BetragExklMwSt += SummeExklMwSt.Value;
                }
            }

            this.CC_BetragExcl.LockContents = false;
            this.CC_BetragExcl.Text = BetragExklMwSt.ToString("#,##0.00");
            this.CC_BetragExcl.LockContents = true;
            SummeInklMwSt = (from MwSt in invXML.InvDetails.TblMwStSummen
                             select MwSt.spGesamtBetrag).Sum();
            SummeMwSt = (from MwSt in invXML.InvDetails.TblMwStSummen
                             select MwSt.spMwStBetrag).Sum();
            BetragInklMwSt = SummeInklMwSt.Value;
            BetragMwSt = SummeMwSt.Value;
            this.CC_MwSt.LockContents = false;
            this.CC_MwSt.Text = BetragMwSt.ToString("#,##0.00");
            this.CC_MwSt.LockContents = true;
            this.CC_Rechnungsbetrag.LockContents=false;
            this.CC_Rechnungsbetrag.Text = BetragInklMwSt.ToString("#,##0.00");
            this.CC_Rechnungsbetrag.LockContents = true;

            FillDocTable(this.Tables[docMwstTab],
                invXML.InvDetails.Tables[invXML.InvDetails.TblMwStSummen.TableName],
                dtMwStColName, dtMwStColFmt, false, 3);

        }
        /// <summary>
        /// Skonto Tabelle aufbauen
        /// </summary>
        private void FillSkontoTabInDoc()
        {
            // spSkontoBetrag berechnen
            foreach (DsInvoice.TblInvSkontoRow sRow in invXML.InvDetails.TblInvSkonto)
            {
                // Rechnungsbetrag neu in die Tabelle eintragen, damit die Skto Beträge neu berechnet werden
                sRow.spBasisBetrag = BetragInklMwSt;
            }
            FillDocTable(this.Tables[docSkontoTab],
                invXML.InvDetails.Tables[invXML.InvDetails.TblInvSkonto.TableName],
                dtSkontoColName,
                dtSkontoColFmt,
                false,
                0);
        }
        /// <summary>
        /// Übertagen aller Tabbellen (Details, MWst und Skonto) in das Word ebDoc
        /// </summary>
        public void UpdateDocDetails()
        {
            // 1. Detailstablle auffüllen
            FillDocTable(this.Tables[docDetailsTab], 
                invXML.InvDetails.Tables[invXML.InvDetails.TblInvDetails.TableName], 
                dtDetailsColName, 
                dtDetailsColFmt, 
                true,
                0);
            // 2. MwSt Block füllen
            FillMwStTabInDoc();
            // 3. SkontoTabelle füllen
            FillSkontoTabInDoc();

        }
        /// <summary>
        /// Füllt die angegebene Word Tabelle mit den Daten aus der DataTable
        /// </summary>
        /// <param name="docTable">Word Tabelle</param>
        /// <param name="dtTab">DataTable mit den Daten</param>
        /// <param name="colTab">String Tabelle mit den Namen der DataTable Columns in der Reihenfolge wie diese in der Word Tabelle vorkommen</param>
        /// <param name="fmtTab">String Tabelle mit den Format Strings für dezimalwerte</param>
        /// <param name="FirstPos">Soll in der 1. Spalte ein Positionszähler geführt werden</param>
        /// <param name="KeepRows">Anzahl der Zeilnen die am Ende der Tabelle nicht gelöscht werden dürfen</param>
        public void FillDocTable(Word.Table docTable, 
            DataTable dtTab, 
            string[] 
            colTab, 
            string[] 
            fmtTab, 
            bool FirstPos,
            int KeepRows)
        {


            UnprotectDoc();
            // Details in Tabelle einfügen
            // Word.Table docDtTable = this.Tables[docDetailsTab];

            int totRowCnt =docTable.Rows.Count;
            // Alle zeilen nach der 2. Zeile löschen
            for (int i = (totRowCnt-KeepRows); i > 2 ; i--)
            {
                docTable.Rows[i].Delete();
            }

            int pos = 0;
            Word.Row cRow = null;
            Word.Cell cCell = null;
            string dtCol = string.Empty;
            string wert = string.Empty;
            int offs = 0;
            object lastRow = new object();

            if (FirstPos == true)
            {
                offs = 2;
            }
            else
            {
                offs = 1;
            }
            cRow = docTable.Rows[2];
            for (int i = 1; i < cRow.Cells.Count + 1; i++)
            {
                cCell = cRow.Cells[i];
                cCell.Range.Text = "";
            }

            for (int ir = 0; ir < dtTab.Rows.Count; ir++)
            {

                if (ir == 0)
                {
                    cRow = docTable.Rows[2];
                }
                else
                {
                    if (KeepRows>0)
                    {
                        lastRow = cRow;
                        cRow = docTable.Rows.Add(ref lastRow); // neue Tabellenzeile einfügen 
                    }
                    else
                    {
                        cRow = docTable.Rows.Add(ref missing); // neue Tabellenzeile einfügen 
                    }
                }
                cRow.Select();
                for (int i = 1; i < (colTab.Length+offs); i++)
                {
                    cCell = cRow.Cells[i];
                    pos = cCell.ColumnIndex;
                    if ((pos == 1) && (FirstPos == true)) // Details Positionsnr
                    {
                        cCell.Range.Text = string.Format("{0}", i);
                    }
                    else
                    {
                        dtCol = colTab[pos - offs];
                        wert = dtTab.Rows[ir][dtCol].ToString();

                        if (fmtTab[pos - offs] != "")
                        {
                            cCell.Range.Text = FormatDecimal(fmtTab[pos - offs], wert);

                        }
                        else
                        {
                            cCell.Range.Text = wert;

                        }
                    }

                }

            }
            ProtectDoc();

        }
        public bool IsMwStInSettings(decimal MwSt)
        {
            bool retVal = true;

            int cnt = 0;
            DataRow[] rows = invXML.InvDetails.TblMWST.Select("spMwSt='" + MwSt.ToString() + "'");
            cnt = rows.Count();
            if (cnt == 0)
            {
                retVal = false;
            }
            return retVal;
        }

        public bool IsMwStUsedInDetails(decimal MwSt)
        {
            bool retVal = true;

            int cnt = 0;
            DataRow[] rows = invXML.InvDetails.TblInvDetails.Select("spMwSt='" + MwSt.ToString() + "'");
            cnt = rows.Count();
            if (cnt==0)
            {
                retVal = false;
            }
            return retVal;
        }
        /// <summary>
        /// Kopiert den Inhalt der hier verwalteten Skonto Tabelle in die des Forms
        /// </summary>
        /// <param name="myDs">Dataset des Forms</param>
        public void FillSkontoTable(DsInvoice myDs)
        {
            CopyTable(invXML.InvDetails, myDs, myDs.TblInvSkonto.TableName);
        }
        /// <summary>
        /// Kopiert den Inhalt der hier verwalteten Details und MwST Tabelle in die des Forms
        /// </summary>
        /// <param name="myDs"></param>
        public void FillDetailsDataGrid(DsInvoice myDs)
        {
            CopyTable(invXML.InvDetails, myDs, myDs.TblInvDetails.TableName);
            CopyTable(invXML.InvDetails, myDs, myDs.TblMWST.TableName);
        }
        /// <summary>
        /// Ruft die Methode SaveXML zum speichern des CustomXMLPart als XML Datei auf.
        /// <see cref="InvoiceXML.SaveXML"/>
        /// </summary>
        /// <param name="AlsVorlage">Gibt an ob das XML als Vorlage oder ebInterface Rechnung gespeichert wird</param>
        public void SaveXML(bool AlsVorlage)
        {
            invXML.InvBankCountry = XlateTables.FindShortcut(this.CC_BankCountry.Text);
            invXML.InvBillerCountry = XlateTables.FindShortcut(this.CC_BillerCountry.Text);
            invXML.InvCurrency = this.CC_Currency.Text;
            invXML.InvRecipientCountry = XlateTables.FindShortcut(this.CC_RecipientCountry.Text);
            invXML.InvDocType = XlateTables.FindDocTypeEnglish(this.CC_InvoiceType.Text); // translation needed
            invXML.InvDocTitle = this.CC_DocumentTitle.Text;

            invXML.SaveXML(InvoiceXMLPart, AlsVorlage);
        }
        /// <summary>
        /// Löscht das aktuelle CustomXMLPart und lädt ein neues
        /// </summary>
        public void LoadTemplateXML()
        {
            string xmldata = invXML.LoadXMLTemplate();
            if (xmldata != "")
            {
                UnprotectDoc();
                try
                {
                    Application.ActiveDocument.CustomXMLParts.SelectByID(InvoiceXMLPartID).Delete();
//                    InvoiceXMLPart.Delete();
                    InvoiceXMLPartID = string.Empty;
                    InvoiceXMLPart = invXML.AddCustomXmlPart(xmldata);

                    invXML.InvDetails.LoadMwStTab();
                    bool retVal = invXML.LoadDetailsTable(InvoiceXMLPart, invXML.InvDetails);
                    if (retVal==false)
                    {
                        throw (new Exception("Rechnungsdetails konnten nicht geladen werden."));
                    }
                    invXML.LoadSkontoTable(InvoiceXMLPart, invXML.InvDetails); // Muss nach InitDoc liegen damit auf die ContentControls zugegriffen werden kann

                    UpdateDocDetails();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Fehler bei Load Template\r\n" + ex.Message, "XML Vorlage laden", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                ProtectDoc();
            }

        }
        public string GetInvoiceDate()
        {
            string datum = string.Empty;
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(InvoiceXML.xPathInvDate);
            datum = vnode.Text;
            return datum;
        }
        /// <summary>
        /// Returns the AssemblyDescription Attribute
        /// </summary>
        /// <returns></returns>
        public string GetSVNInfo()
        {
            string info = string.Empty;
            Assembly asm = Assembly.GetExecutingAssembly();
            //info = asm.FullName;
            string svnInfo = string.Empty;
            object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), true);
            if (attributes.Length > 0)
            {
                AssemblyDescriptionAttribute descriptionAttribute = attributes[0] as AssemblyDescriptionAttribute;
                svnInfo = descriptionAttribute.Description;
            }
            return svnInfo;
        }

        /// <summary>
        /// Returns the Assmebly Title Attribute
        /// </summary>
        /// <returns></returns>
        public string GetAsmTitle()
        {
            string info = string.Empty;
            Assembly asm = Assembly.GetExecutingAssembly();
            //info = asm.FullName;
            string svnInfo = string.Empty;
            object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), true);
            if (attributes.Length > 0)
            {
                AssemblyTitleAttribute descriptionAttribute = attributes[0] as AssemblyTitleAttribute;
                svnInfo = descriptionAttribute.Title;
            }
            return svnInfo;
        }
        #endregion

        #region ContentControl Events
        private void CC_InvoiceDate_StoreUpdating(object sender, Microsoft.Office.Tools.Word.ContentControlStoreUpdatingEventArgs e)
        {
            try
            {
                Rechnungsdatum = DateTime.Parse(e.Content);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Rechnungsdatum ungültig.");
            }
            DataRow[] skRows = invXML.InvDetails.TblInvSkonto.Select();
            foreach (DsInvoice.TblInvSkontoRow SkRow in skRows)
            {
                invXML.InvDetails.TblInvSkonto.UpdateSkontoDatum(SkRow);
            }

            //try
            //{
            //    FillSkontoTabInDoc();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("Fehler bei Skontoupdate\r\n" + ex.Message);
            //    throw;
            //} 
            return;
        }
        

        private void CC_RecipientVATID_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (CC_RecipientVATID.ShowingPlaceholderText == true)
            {
                MessageBox.Show("Die VAT-ID des Empfänger darf in ebInterface 3.0 nicht leer sein. Geben sie ein gültige VAT-ID oder 00000000 ein.");
            }

        }

        private void CC_DueDate_StoreUpdating(object sender, Microsoft.Office.Tools.Word.ContentControlStoreUpdatingEventArgs e)
        {
            try
            {
                FaelligDatum = DateTime.Parse(e.Content);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fälligkeitsdatum ungültig.");
            }

        }

        #endregion

    }
}
